package com.chushouya.order.service.admin.impl;

import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.general.framework.data.redis.RedisLock;
import com.chushouya.manager.service.common.AlipayClientCommonService;
import com.chushouya.order.constants.IdentityTypeEnum;
import com.chushouya.order.constants.OrderPayStatusEnum;
import com.chushouya.order.constants.PaymentStatusEnum;
import com.chushouya.order.constants.TradeTypeEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.PaymentLogEntity;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dao.repository.PaymentLogRepository;
import com.chushouya.order.dto.admin.paymentlog.PaymentInfoDTO;
import com.chushouya.order.dto.admin.paymentlog.PaymentResultDTO;
import com.chushouya.order.service.admin.AlipayOrderPayService;
import com.chushouya.order.service.common.impl.OrderLogServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AlipayOrderPayServiceImpl implements AlipayOrderPayService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private PaymentLogRepository paymentLogRepository;

    @Resource
    private AlipayClientCommonService alipayClientCommonService;

    @Resource
    private RedisLock redisLock;
    private OrderLogServiceImpl orderLogServiceImpl;


    private OrderEntity getOrder(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        return orderEntity;
    }


    /**
     * 客服订单支付
     */
    @Override
    public PaymentResultDTO alipayOrderPay(PaymentInfoDTO dto) {
        log.info("开始处理客服订单支付，订单ID：{}，收款账号：{}", dto.getOrderId(), dto.getAccountNumber());
//        final String cacheKey = Strings.format("order_pay:{}", dto.getOrderId());
//        boolean lockAcquired = redisLock.tryLock(cacheKey, 5L, TimeUnit.SECONDS);
//        if (!lockAcquired) {
//            return PaymentResultDTO.fail("系统繁忙，请稍后重试");
//        }
        
        PaymentLogEntity paymentLog = null;
        try {
            // 1.验证订单信息和请求信息 判断订单是否可以支付查询PaymentLog是否有成功的支付记录
            OrderEntity order = validateOrderAndPayment(dto);

            // 2.生成支付日志
            paymentLog = createPaymentLog(order, dto);

            // 3.调用支付宝支付接口
            Integer paymentSuccess = callAlipayTransfer(order, dto, paymentLog);

            // 4.更新支付日志
            updatePaymentLog(paymentLog, paymentSuccess);

            // 5.返回支付结果
            if (Objects.equals(paymentSuccess, PaymentStatusEnum.SUCCESS.value())) {
                log.info("客服订单支付成功，订单ID：{}，支付日志ID：{}", dto.getOrderId(), paymentLog.getLogId());
                return PaymentResultDTO.success(paymentLog.getLogId(), paymentLog.getOutBizNo(), paymentLog.getTradeNo());
            } else if (Objects.equals(paymentSuccess, PaymentStatusEnum.PROCESSING.value())) {
                log.info("客服订单支付处理中，订单ID：{}，支付日志ID：{}", dto.getOrderId(), paymentLog.getLogId());
                return PaymentResultDTO.processing(paymentLog.getLogId(), paymentLog.getOutBizNo());
            } else {
                log.warn("客服订单支付失败，订单ID：{}，支付日志ID：{}", dto.getOrderId(), paymentLog.getLogId());
                return PaymentResultDTO.fail("支付失败，请联系客服处理");
            }
            
        } catch (Exception e) {
            log.error("客服订单支付处理异常，订单ID：{}，异常信息：{}", dto.getOrderId(), e.getMessage(), e);
            
            // 如果支付日志已创建，更新为失败状态
            if (paymentLog != null) {
                try {
                    updatePaymentLog(paymentLog, PaymentStatusEnum.FAIL.value());
                } catch (Exception updateEx) {
                    log.error("更新支付日志失败状态异常：{}", updateEx.getMessage());
                }
            }
            
            return PaymentResultDTO.fail("支付处理异常：" + e.getMessage());
        }
//        finally {
//            // 只有成功获取锁的情况下才释放锁
//            if (lockAcquired) {
//                redisLock.unlock(cacheKey);
//            }
//        }
    }

    /**
     * 验证订单信息和支付记录
     */
    private OrderEntity validateOrderAndPayment(PaymentInfoDTO dto) {
        // 验证订单存在
        OrderEntity order = getOrder(dto.getOrderId());

        // 验证订单状态是否可以支付
        if (!OrderPayStatusEnum.UNPAID.value().equals(order.getPayStatus())) {
            throw Ex.business("订单状态不允许支付，当前支付状态：" + order.getPayStatus());
        }

        // 验证订单金额
        if (order.getCompletePrice() == null || order.getCompletePrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw Ex.business("订单金额异常，无法支付");
        }

        // 检查是否已有成功的支付记录
        List<PaymentLogEntity> existingPayments = paymentLogRepository.selectByOrderId(dto.getOrderId());
        if (Lists.isNotEmpty(existingPayments)) {
            for (PaymentLogEntity payment : existingPayments) {
                if (Boolean.TRUE.equals(payment.getStatus())) {
                    throw Ex.business("订单已有成功支付记录，不能重复支付");
                }
            }
        }

        // 验证收款信息
        if (Strings.isBlank(dto.getAccountName()) || Strings.isBlank(dto.getAccountNumber())) {
            throw Ex.business("收款账号信息不完整");
        }

        return order;
    }

    /**
     * 生成支付日志
     */
    private PaymentLogEntity createPaymentLog(OrderEntity order, PaymentInfoDTO dto) {
        PaymentLogEntity paymentLog = new PaymentLogEntity();
        paymentLog.setOrderId(order.getOrderId());
        paymentLog.setOrderNo(order.getOrderNo());
        paymentLog.setPayAmount(order.getCompletePrice());
        paymentLog.setPayChannel("alipay");
        paymentLog.setPayType("transfer");
        paymentLog.setStatus(PaymentStatusEnum.PROCESSING.value()); // 初始状态为待支付
        paymentLog.setOpenId(dto.getAccountNumber());
        paymentLog.setCreateTime(new Date());
        paymentLog.setUpdateTime(new Date());

        // 生成商户转账单号
        String outBizNo = Strings.format("{}-{}", order.getOrderNo(), TradeTypeEnum.BALANCE.value());
        paymentLog.setOutBizNo(outBizNo);

        // 保存支付日志
        paymentLogRepository.insertSelective(paymentLog);

        log.info("创建支付日志成功，支付日志ID：{}，商户单号：{}", paymentLog.getLogId(), outBizNo);
        return paymentLog;
    }

    /**
     * 调用支付宝转账接口
     */
    private Integer callAlipayTransfer(OrderEntity order, PaymentInfoDTO dto, PaymentLogEntity paymentLog) {
        try {
            log.info("开始调用支付宝转账接口，订单号：{}，金额：{}，收款账号：{}",
                    order.getOrderNo(), order.getCompletePrice(), dto.getAccountNumber());

            // 调用支付宝转账接口
            AlipayFundTransUniTransferResponse response = alipayClientCommonService.fundTransUniTransfer(
                    paymentLog.getOutBizNo(),           // 商户转账单号
                    order.getCompletePrice().toString(),           // 转账金额
                    "订单回收款-" + order.getOrderNo(),    // 转账标题
                    "出手鸭回收款",                // 转账备注
                    dto.getAccountNumber(),             // 收款账号
                    IdentityTypeEnum.ALIPAY_LOGON_ID.name(),                 // 账号类型：支付宝登录号
                    dto.getAccountName()                // 收款人姓名
            );

            // 更新支付宝转账单号
            if (response != null && Strings.isNotBlank(response.getOrderId())) {
                paymentLog.setTradeNo(response.getOrderId());
                paymentLog.setResponseData(response.toString());
            }

            if (response != null && Strings.isNotBlank(response.getSubMsg())) {
                throw Ex.business("支付宝转账失败：{}" , response.getSubMsg());
            }

            // 判断转账是否成功
            boolean success = response != null && "SUCCESS".equals(response.getStatus());

            log.info("支付宝转账接口调用完成，订单号：{}，结果：{}，支付宝单号：{}",
                    order.getOrderNo(), success, response != null ? response.getOrderId() : "无");

            return success ? PaymentStatusEnum.SUCCESS.value() : PaymentStatusEnum.FAIL.value();

        } catch (Exception e) {
            log.error("调用支付宝转账接口异常，订单号：{}，异常信息：{}", order.getOrderNo(), e.getMessage(), e);

            // 记录异常信息到支付日志
            paymentLog.setResponseData("转账异常：" + e.getMessage());

            throw Ex.business("调用支付接口异常：{}", e.getMessage());
        }
    }

    /**
     * 更新支付日志
     */
    private void updatePaymentLog(PaymentLogEntity paymentLog, Integer paymentSuccess) {
        paymentLog.setStatus(paymentSuccess);
        paymentLog.setUpdateTime(new Date());

        // 更新支付日志
        paymentLogRepository.updateByPrimaryKeySelective(paymentLog);

        log.info("更新支付日志完成，支付日志ID：{}，支付状态：{}", paymentLog.getLogId(), paymentSuccess);
    }
}
